//
//  BYAddImageView.m
//  ZhaoQiPei
//
//  Created by 找汽配 on 16/2/29.
//  Copyright © 2016年 祥运. All rights reserved.
//

#import "XYImageSelectCollectionView.h"
#import "XYImageSelectCollectionViewCell.h"
#import "XYImageSelectModel.h"

@interface XYImageSelectCollectionView () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, XYImageSelectCollectionViewCellDelegate>

@property (nonatomic, weak) UILongPressGestureRecognizer * longPressGestureRecognizer;

@end

@implementation XYImageSelectCollectionView

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.dataSource = self;
    self.delegate = self;
    [self registerNib:[UINib nibWithNibName:@"XYImageSelectCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:kXYImageSelectCollectionViewCellReuseIdentifier];

    self.models = [NSMutableArray array];
    self.maxNumberOfImages = 1;
    self.editEnabled = YES;
    self.selectImage = [UIImage imageNamed:@"xy_add_icon"];
    self.deleteImage = [UIImage imageNamed:@"xy_delete_icon"];
}

#pragma mark - Controller

- (void)setImagesWithImages:(NSArray<UIImage *>*)images {
    [images enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        XYImageSelectModel * model = [XYImageSelectModel model];
        model.type = XYImageSelectTypeImage;
        model.image = obj;
        model.action = self.modelAction;
        [self.models addObject:model];
    }];
    [self reloadData];
}

- (void)setImagesWithModels:(NSArray<XYImageSelectModel *>*)models {
    [models enumerateObjectsUsingBlock:^(XYImageSelectModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.type = XYImageSelectTypeImage;
        obj.action = self.modelAction;
        [self.models addObject:obj];
    }];
    [self reloadData];
}

- (void)didSelectImagesWithImages:(NSArray<UIImage *>*)images {
    if (self.models.count + images.count > self.maxNumberOfImages) {
        if (self.action && [self.action respondsToSelector:@selector(imageSelectViewWarnForTooManyImages)]) {
            [self.action imageSelectViewWarnForTooManyImages];
        }
        return;
    }
    [images enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        XYImageSelectModel * model = [XYImageSelectModel model];
        model.type = XYImageSelectTypeImage;
        model.image = obj;
        model.action = self.modelAction;
        [model uploadImage];
        [self.models addObject:model];
    }];
    [self reloadData];
}

- (void)didSelectImagesWithModels:(NSArray<XYImageSelectModel *>*)models {
    if (self.models.count + models.count > self.maxNumberOfImages) {
        if (self.action && [self.action respondsToSelector:@selector(imageSelectViewWarnForTooManyImages)]) {
            [self.action imageSelectViewWarnForTooManyImages];
        }
        return;
    }
    [models enumerateObjectsUsingBlock:^(XYImageSelectModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.type = XYImageSelectTypeImage;
        obj.action = self.modelAction;
        [obj uploadImage];
        [self.models addObject:obj];
    }];
    [self reloadData];
}

- (void)setCanMove:(BOOL)canMove {
    if (canMove) {
        // 添加长按手势
        UILongPressGestureRecognizer * recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGestureRecognizer:)];
        [self addGestureRecognizer:recognizer];
        self.longPressGestureRecognizer = recognizer;
    }
    else {
        [self removeGestureRecognizer:self.longPressGestureRecognizer];
        self.longPressGestureRecognizer = nil;
    }
}

- (void)setEditEnabled:(BOOL)editEnabled {
    _editEnabled = editEnabled;
    [self reloadData];
}

- (BOOL)isUploaded {
    __block BOOL uploaded = YES;
    [self.models enumerateObjectsUsingBlock:^(XYImageSelectModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.isUploading || obj.imageURL.length == 0) {
            uploaded = NO;
            *stop = YES;
        }
    }];
    return uploaded;
}

- (NSArray<NSString *> *)imageURLs {
    NSMutableArray * mArray = [NSMutableArray arrayWithCapacity:self.models.count];
    [self.models enumerateObjectsUsingBlock:^(XYImageSelectModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.imageURL) {
            [mArray addObject:obj.imageURL];
        }
    }];
    return [mArray copy];
}

- (void)longPressGestureRecognizer:(UILongPressGestureRecognizer *)recognizer {
    switch (recognizer.state)
    {
        // 手势开始
        case UIGestureRecognizerStateBegan:
        {
            // 判断手势落点位置是否在row上
            NSIndexPath * indexPath = [self indexPathForItemAtPoint:[recognizer locationInView:self]];
            if (!indexPath) {
                break;
            }
            UICollectionViewCell * cell = [self cellForItemAtIndexPath:indexPath];
            [self bringSubviewToFront:cell];
            // iOS9方法 移动cell
            [self beginInteractiveMovementForItemAtIndexPath:indexPath];
            break;
        }
        // 手势改变
        case UIGestureRecognizerStateChanged:
        {
            // iOS9方法 移动过程中随时更新cell位置
            [self updateInteractiveMovementTargetPosition:[recognizer locationInView:self]];
            break;
        }
        // 手势结束
        case UIGestureRecognizerStateEnded:
        {
            // 判断手势落点位置是否在row上
            NSIndexPath * indexPath = [self indexPathForItemAtPoint:[recognizer locationInView:self]];
            if (indexPath && indexPath.item < self.models.count) {
                // iOS9方法 移动结束后关闭cell移动
                [self endInteractiveMovement];
            }
            else {
                [self cancelInteractiveMovement];
            }
            break;
        }
        // 手势其他状态
        default:
            [self cancelInteractiveMovement];
            break;
    }
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.editEnabled) {
        return self.models.count + (self.models.count >= self.maxNumberOfImages ? 0 : 1);
    }
    else {
        return self.models.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    XYImageSelectModel * model = nil;
    if (indexPath.item < self.models.count) {
        model = self.models[indexPath.row];
    }
    else {
        model = [XYImageSelectModel model];
        model.type = XYImageSelectTypeSelect;
    }
    XYImageSelectCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:kXYImageSelectCollectionViewCellReuseIdentifier forIndexPath:indexPath];
    cell.delegate = self;
    [cell reloadData:model];
    [cell setSelectImage:self.selectImage];
    [cell setDeleteImage:self.deleteImage];
    [cell setEditEnabled:self.isEditEnabled];
    return cell;
}

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item < self.models.count) {
        XYImageSelectModel * model = self.models[indexPath.row];
        if (self.action && [self.action respondsToSelector:@selector(imageSelectCollectionViewDidSelectImageWithModel:)]) {
            [self.action imageSelectCollectionViewDidSelectImageWithModel:model];
        }
    }
}

- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item < self.models.count) {
        return YES;
    }
    else {
        return NO;
    }
}

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    // 取出移动row数据
    XYImageSelectModel * model = self.models[sourceIndexPath.item];
    // 从数据源中移除该数据
    [self.models removeObject:model];
    // 将数据插入到数据源中的目标位置
    [self.models insertObject:model atIndex:destinationIndexPath.item];
}

#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.action && [self.action respondsToSelector:@selector(imageSelectCollectionViewSizeForItem)]) {
        return [self.action imageSelectCollectionViewSizeForItem];
    }
    else {
        return CGSizeZero;
    }
}

#pragma mark - XYImageSelectCollectionViewCellDelegate

- (void)imageSelectCollectionViewCellShouldSelectImage {
    NSInteger count = self.maxNumberOfImages - self.models.count;
    if (count > 0) {
        if (self.action && [self.action respondsToSelector:@selector(imageSelectCollectionViewShouldSelectImagesWithCount:)]) {
            [self.action imageSelectCollectionViewShouldSelectImagesWithCount:count];
        }
    }
}

- (void)imageSelectCollectionViewCellShouldDeleteImageWithImageSelectModel:(XYImageSelectModel *)model {
    [self.models removeObject:model];
    [self reloadData];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/


@end
